package org.xyl.game.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xyl.game.dao.RoomDao;
import org.xyl.game.dao.RoominfoDao;
import org.xyl.game.dao.StartDao;
import org.xyl.game.dto.InquireRoomRet;
import org.xyl.game.entity.Room;
import org.xyl.game.entity.Userinroom;
import org.xyl.game.entity.Start;
import org.xyl.game.service.RoomService;

import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    private RoomDao roomDao;
    @Autowired
    private RoominfoDao roominfoDao;
    @Autowired
    private StartDao startDao;

    @Override
    @Transactional
    public String createRoom(String username) {
        Room room = new Room();
        room.setBluecount(0);
        room.setRedcount(0);
        room.setRednumber(1);
        room.setBluenumber(0);
        Room save = roomDao.save(room);
        Userinroom userinroom = new Userinroom();
        userinroom.setRoomid(room.getRoomid());
        userinroom.setTeam("red");
        userinroom.setUsername(username);
        roominfoDao.save(userinroom);
        Start start = new Start();
        start.setRoomid(room.getRoomid());
        start.setFlag(0);
        startDao.save(start);
        return room.getRoomid() + "";
    }

    @Override
    @Transactional
    public boolean joinRoom(int roomid, String username, String team) {
        Userinroom userinroom = new Userinroom();
        userinroom.setRoomid(roomid);
        userinroom.setUsername(username);
        userinroom.setTeam(team);
        roominfoDao.save(userinroom);

        Room byId = roomDao.getByRoomid(roomid);
        if (byId == null) {
            return false;
        }
        if (team.equals("red")) {
            byId.setRednumber(byId.getRednumber() + 1);
        } else {
            byId.setBluenumber(byId.getBluenumber() + 1);
        }
        roomDao.save(byId);
        return true;

    }

    @Override
    @Transactional
    public InquireRoomRet inquireRoom(int roomid) {
        List<Userinroom> redInfo = roominfoDao.findByRoomidAndTeam(roomid, "red");
        List<Userinroom> blueInfo = roominfoDao.findByRoomidAndTeam(roomid, "blue");
        Start byRoomid = startDao.getByRoomid(roomid);
        InquireRoomRet inquireRoomRet = new InquireRoomRet();
        inquireRoomRet.setRedInfo(redInfo);
        inquireRoomRet.setBlueInfo(blueInfo);
        inquireRoomRet.setFlag(byRoomid.getFlag());
        return inquireRoomRet;

    }
}
